package com.agency8x.controller;

import com.agency8x.bean.LoginParamBean;
import com.agency8x.bean.LoginErrorBean;
import com.agency8x.bean.ResultInfoBean;
import com.agency8x.config.AppConf;
import com.agency8x.interceptor.CheckLoginInterceptor;
import com.agency8x.model.LoginModel;
import com.agency8x.validator.LoginValidator;
import com.agency8x.web.util.ControllerUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

/**
 * 登录页控制器
 * 
 * @author SoChishun
 *
 */
public class LoginController extends Controller {

	// 登录页面
	public void index() {
		int maxLimit = 5; // 最大错误次数
		LoginErrorBean errorBean = LoginModel.getLoginErrorInfo(this);
		if (null != errorBean && !errorBean.checkLoginable(5)) {
			this.renderText("您已经登录错误超过" + maxLimit + "次，请5分钟后再登录!");
			return;
		}
		setAttr("showCaptcha", LoginModel.checkHasLoginError(this));
		render("index.html");
	}

	// 登录表单提交动作
	@Before(LoginValidator.class)
	public void doLogin() {
		// 收集表单信息
		LoginParamBean loginBean = new LoginParamBean();
		loginBean.setUserName(this.getPara("user_name"));
		loginBean.setPassword(this.getPara("password"));

		// 登录操作
		ResultInfoBean result = LoginModel.CheckLogin(loginBean);
		if (result.getResult()) {
			// 登录成功
			LoginModel.clearLoginErrorInfo(this);
			setSessionAttr(AppConf.loginSessionID, result.getObjectParam()); // LoginModel
			redirect("/index");
		} else {
			// 登录失败
			LoginModel.setLoginErrorCount(this);
			ControllerUtil.renderDisptchJumpError(this, new String[] { result.getMessage() }, "/login");
		}

	}

	// 注销登录动作
	public void logout() {
		this.redirect("/login");
	}
}
